<html>
  <head>
    <meta name="viewport" content="width=device-width" />
    <script type="text/javascript">
      // onerror need to report errors which happens on WKWebView.loadHTMLString
      window.onerror = function(msg, url, line, column, error) {
        if (window.webkit) {
          window.webkit.messageHandlers.hcaptcha.postMessage({ "error": 1 });
        } else {
          console.log("Error:", error);
        }
      };
    </script>
    <script type="text/javascript">
      var key = "${apiKey}";
      var endpoint = "${endpoint}";
      var shouldFail = ${shouldFail};
      var rqdata = "${rqdata}";
      var theme = ${theme};
      var debugInfo = JSON.parse('${debugInfo}');

      const themeType = typeof theme;
      console.assert(themeType === "string" || themeType === "object", "invalid theme object");
      console.assert(Array.isArray(debugInfo), "invalid type");

      var post = function(value) {
          window.webkit.messageHandlers.hcaptcha.postMessage(value);
      };

      var execute = function() {
          if (shouldFail) {
              post({error: 15}); // .sessionTimeout
          } else {
              if (rqdata) {
                  post({"log": rqdata});
              }
              var messageToPost = ${message};
              if (messageToPost.action === "openExternalPage") {
                  document.getElementById("external-link").click();
              }
              post(messageToPost);
              if (messageToPost && messageToPost.token || messageToPost.action === "showHCaptcha") {
                  setTimeout(function() {
                      post({ action: "onOpen" });
                  }, 100);
              }
          }
      };

      var reset = function() {
          shouldFail = false;
          post({ action: "didLoad" });
      };

      post({ action: "didLoad" });

      // clear global error handle, rest will be handled in WKWebView.evaluateJavaScript closure
      window.onerror = null;
    </script>
  </head>
  <body>
    <span id="submit" style="visibility: hidden;"></span>
    <a id="external-link" target="_blank" href="https://hcaptcha.com" rel="noopener">Test external</a>
  </body>
</html>
